#!/usr/bin/env python

HEADER_FILE     = 'header.html'
FOOTER_FILE     = 'footer.html'
DEBUG           = False
HTTP_HEADERS    = { 'X-SID' : '8720a194274c761371cffdbbdd74d02f' }
ADMIN_EMAIL     = ('senux@senux.com', )

__author__      = 'senux@senux.com (Seongsu Lee)'


import md5
import os
import sys
import time

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app


class User:
    user        = None
    login_url   = None
    logout_url  = None
    email       = None
    admin       = False
    nickname    = None

    def __init__(self, request_uri):
        self.user           = users.get_current_user()
        self.login_url      = users.create_login_url(request_uri)
        self.logout_url     = users.create_logout_url(request_uri)
        if self.user:
            self.email      = self.user.email()
            self.email_md5  = md5.new(self.email).hexdigest
            #self.admin      = users.is_current_user_admin()
            self.admin      = True if self.email in ADMIN_EMAIL else False
            self.nickname   = self.user.nickname().split('@', 1)[0].strip()

class SeongsuNetwork(webapp.RequestHandler):
    module_name = None
    module      = None

    def get(self):
        self.serve()

    def post(self):
        self.serve()

    def serve(self):
        sys.path.append(os.getcwd())
        self.started_time = time.time()
        self.module       = __import__(self.module_name)
        user              = User(self.request.uri)
        control, hheader, bbody, return_url, void = self.module.bbody(self.request, user)

        # HTTP header
        hheader.update(HTTP_HEADERS)
        for key in hheader:
            self.response.headers[key.strip()] = hheader[key]

        if return_url:
            # redirect without HTTP body
            self.redirect(return_url)
        else:
            # HTTP body (header, body, footer)
            if control['bheader']:
                bheader = self.bheader(user, void)
                self.response.out.write('%s' % bheader)
            if control['bbody']:
                self.response.out.write('%s' % bbody)
            if control['bfooter']:
                bfooter = self.bfooter(user, void)
                self.response.out.write('%s' % bfooter)

    def bheader(self, user, void):
        void.update(headerfooter.header())
        template_values = {
            'user'    : user,
            'void'    : void,
            'elapsed' : time.time() - self.started_time,
        }
        path = os.path.join(os.path.dirname(__file__), HEADER_FILE)
        return template.render(path, template_values)

    def bfooter(self, user, void):
        template_values = {
            'user'    : user,
            'void'    : void,
        }
        path = os.path.join(os.path.dirname(__file__), FOOTER_FILE)
        return template.render(path, template_values)

class Blog(SeongsuNetwork):
    module_name = 'blog'

class Delicious(SeongsuNetwork):
    module_name = 'delicious'

class RSS(SeongsuNetwork):
    module_name = 'rss'

class Front(SeongsuNetwork):
    module_name = 'front'

def main():
    template.register_template_library('common.smartbr')
    application = webapp.WSGIApplication(
            [ ('/blog/',        Blog), 
              ('/delicious/',   Delicious), 
              ('/rss/',         RSS), 
              ('/',             Front),
              ], debug = DEBUG)
    run_wsgi_app(application)

if __name__ == '__main__':
    sys.path.append(os.getcwd())
    import headerfooter

    main()

